var defaults = {
	result: [],
	detailList: [],
	dataList: [],
	detailNum: 0,
	cartonNum: 0,
	taskNum: 0,
	cartonList: []
}

var detailIndex = 0,
	cartonIndex = 0,
	taskIndex = 0

var report = {
	reportData: null,
	cartonObj: {
		"Rows": []
	},
	cartonList: [],
	detailObj: {
		"Rows": []
	}
}

var loader = $(".cssload-loader")
var log = console.log.bind(console)

var resData = function(taskChange) {
	$.ajax({
		url: "taskDTO.json",
		async: false,
		cache: false,
		beforeSend: function() {
			loader.show()
		},
		success: function(result) {
			loader.hide()
			renders(result, taskChange)
			innerReport()
			createGrid()
		},
		error: function() {
			loader.show()
		}
	})
}

var renders = function(result, taskChange) {
//	log(result)
	defaults["result"] = result
	defaults["taskNum"] = result.length
	
	for(var i = 0; i < defaults["taskNum"]; i++) {
		defaults["dataList"][i] = result[i]
	}
	
	show(0)
}

var show = function(index) {
	defaults["detailList"] = []
	report["cartonObj"].Rows = []
	var dataList = defaults["result"][taskIndex].cartonDTOList[index]
	report["reportData"] = defaults["result"][taskIndex].reportData
	for(var i = 0; i < defaults["result"][taskIndex].cartonDTOList.length; i++) {
		var carton = defaults["result"][taskIndex].cartonDTOList[i].carton
		var reportRows = report["cartonObj"].Rows[i] = carton
		report["cartonList"][i] = carton
		//取小数点后3位
		reportRows.weight = toDecimal(reportRows.weight)
		reportRows.ratio = toDecimal(reportRows.ratio)
	}
	var carton = dataList.carton
	var cartonMesh = initBox(carton.length, carton.width, carton.height)
	defaults["cartonList"].push(cartonMesh)
	defaults["cartonNum"] = defaults["result"][taskIndex].cartonDTOList.length
	detailIndex = defaults["detailNum"] = dataList.detailList.length
	report["detailObj"].Rows = dataList.detailList
	for(var i = 0; i < defaults["detailNum"]; i++) {
		var detail = dataList.detailList[i]
		if(!detail.r) {
			var detailMesh = initObject(detail.width, detail.height, detail.length,
				detail.partX, detail.partY, detail.partZ, detail.partName)
		} else {
			var detailMesh = initObject(detail.length, detail.height, detail.width,
				detail.partX, detail.partY, detail.partZ, detail.partName)
		}
		defaults["detailList"].push(detailMesh)
	}
}

var toPercent = function(point) {
	var str = Number(point * 100).toFixed(2)
	str += "%"
	return str
}

var toDecimal = function(x) {
	var f = parseFloat(x)
	if(isNaN(f)) {
		return
	}
	var s = f.toFixed(3)
	return s
}

var refresh = function(taskChange) {
	if(taskChange){
		$("#cartonTab").empty()
		cartonIndex = 0
	} 
	clear()
	for(var i = 0; i < defaults["cartonNum"]; i++) {
		scene.remove(defaults["cartonList"][i])
	}
	for(var i = 0; i < defaults["detailNum"]; i++) {
		scene.remove(defaults["detailList"][i])
	}
	show(cartonIndex)
	$(".report").children().children().html("")
	innerReport()
	createGrid()
}

$("#prevTask").click(function() {
	if(taskIndex <= 0) {
		return
	}
	taskIndex--
	refresh(true)
	tab()
	$("#taskTab").val(taskIndex)
})

$("#nextTask").click(function() {
	if(taskIndex >= defaults["taskNum"] - 1) {
		return
	}
	taskIndex++
	refresh(true)
	tab()
	$("#taskTab").val(taskIndex)
})

$("#taskTab").change(function() {
	taskIndex = $(this).val()
	refresh(true)
	tab()
	$("#taskTab").val(taskIndex)
})

$("#prevCarton").click(function() {
	if(cartonIndex <= 0) {
		return
	}
	cartonIndex--
	refresh()
	$("#cartonTab").val(cartonIndex)
})

$("#nextCarton").click(function() {
	if(cartonIndex >= (defaults["cartonNum"] - 1)) {
		return
	}
	cartonIndex++
	refresh()
	$("#cartonTab").val(cartonIndex)
})

$("#cartonTab").change(function() {
	cartonIndex = $(this).find("option:selected").val()
	refresh()
})

$("#next").click(function() {
	if(detailIndex >= (defaults["detailNum"])) {
		return
	}
	scene.add(defaults["detailList"][detailIndex])
	detailIndex += 1
})

$("#prev").click(function() {
	if(detailIndex <= 0) {
		return
	}
	detailIndex -= 1
	scene.remove(defaults["detailList"][detailIndex])
})

$("#first").click(function() {
	detailIndex = 0
	for(var i = 0; i < defaults["detailNum"]; i++) {
		scene.remove(defaults["detailList"][i])
	}
})

$("#last").click(function() {
	detailIndex = defaults["detailNum"]
	for(var i = 0; i < defaults["detailNum"]; i++) {
		scene.add(defaults["detailList"][i])
	}
})

$(".tab-title-li").click(function() {
	$(".tab-title-li").removeClass("on")
	$(this).addClass("on")
	var tab = $(this).parent().parent().find(".tab-body-li")
	var index = $(this).index() - 1
	tab.addClass("dn")
	tab.eq(index).removeClass("dn")
})

var innerReport = function() {
	var cdiv = new Array(
		getReportData("taskCode"),
		getReportData("volumeOfCargos", false, 1),
		getReportData("volumeOfContainers", false, 1),
		getReportData("uilitationRatio", true),
		getReportData("lossRatio", true),
		getReportData("sumOfCargos"),
		getReportData("areaOfContainers", false, 2),
		getReportData("volumeOfFilers", false, 1),
		getReportData("oneCargoNum"),
		getReportData("partWeight"),
		getReportData("angleBeadWeight"),
		getReportData("fillerWeight"),
		getReportData("nailingWeight"),
		getReportData("paperWeight"),
		getReportData("weight")
	)

	var span = $($(".report")[0]).children("p").children("span")
	for(var i = 0; i < cdiv.length; i++) {
		span[i].appendChild(cdiv[i])
	}

	var sdiv = new Array(
		getCartonList("cartonCode"),
		getCartonList("count"),
		getCartonList("length"),
		getCartonList("width"),
		getCartonList("height"),
		getCartonList("ratio", true),
		getCartonList("weight"),
		getCartonList("layer"),
		getCartonList("order"),
		getCartonList("rule"),
		getCartonList("rule"),
		getCartonList("angleBeadWeight"),
		getCartonList("angleBeadWeight"),
		getCartonList("fillerWeight"),
		getCartonList("nailingWeight"),
		getCartonList("paperWeight")
	)
	var span = $($(".report")[1]).children("p").children("span")
	for(var i = 0; i < sdiv.length; i++) {
		span[i].appendChild(sdiv[i])
	}
}

var createGrid = function() {

	$("#cartionGrid").ligerGrid({
		columns: cartonColumns,
		data: report["cartonObj"],
		pageSize: 20,
		rownumbers: true,
		usePager: true,
		height: window.innerHeight - 80
	})

	$("#detailGrid").ligerGrid({
		columns: detailColumns,
		data: report["detailObj"],
		pageSize: 999,
		rownumbers: true,
		usePager: true,
		height: window.innerHeight - 80,
		pageSizeOptions: [0]
	})
}

/**
 * 
 * @param {String} name
 * @param {Boolean} isPercent
 * @param {Number} computeNum
 */
var getReportData = function(name, isPercent, computeNum) {
	var div = document.createElement("div")
	div.style.display = "inline"
	var value = report["reportData"][name]
	switch(computeNum) {
		case 1:
			//面积
			value = (value / Math.pow(10, 9)).toFixed(3)
			break
		case 2:
			//体积
			value = (value / Math.pow(10, 6)).toFixed(3)
			break
	}
	if(isPercent) {
		div.innerHTML = toPercent(value)
		return div
	}
	div.innerHTML = value
	return div
}

var getCartonList = function(str, isPercent) {
	var div = document.createElement("div")
	div.style.display = "inline"
	if(isPercent) {
		div.innerHTML = toPercent(report["cartonList"][cartonIndex][str])
		return div
	}
	div.innerHTML = report["cartonList"][cartonIndex][str]
	return div
}

var tab = function() {
	for(var i = 0; i < defaults["dataList"].length; i++) {
		var selectObj = document.getElementById("taskTab")
		selectObj[i] = new Option("任务" + (i + 1), i)
	}
	var size = defaults["dataList"][taskIndex].cartonDTOList.length
	for(var j = 0; j < size; j++) {
		var selectObj = document.getElementById("cartonTab")
		selectObj[j] = new Option("纸箱" + (j + 1), j)
	}
}

$(function() {
	$("#layout").ligerLayout({
		rightWidth: 310,
	})
//	$("#canvas-frame").height(window.innerHeight - 5+"px")
	loader.hide()
	init()
	initAxis()
	animation()
	resData()
	tab()
})